<?php

class HdfsUtil {
	
	private $hadoopClient;
	public function  __construct($client = '/home/cloud/software/hadoop/bin/hadoop') {
		$this->hadoopClient = $client;
	}

	public function readDir($path) {
		$cmd=$this->hadoopClient. ' dfs -ls ' . $path;
		$fp = popen($cmd, "r");
		if($fp && !feof($fp)) {
			$head = fgets($fp);
		}
		$files = array();
		while($fp && !feof($fp)){
			$str = trim(fgets($fp));
			if(empty($str)){
				continue;
			}
			$file = new HdfsStat($str);
			$files[] = $file;
		}
		pclose($fp);
		return $files;
	}

	public function openFile($file) {
		$cmd = $this->hadoopClient . " dfs -cat $file";
		$fp = popen($cmd,"r");
		return $fp;
	}

	public function closeFile($handle) {
		pclose($handle);
	}

	public function read($handle, $length = 1024) {
		return fread($handle, $length);
	}

	public function mkdir($dir) {
		$cmd = $this->hadoopClient . " dfs -mkdir $dir";
		exec($cmd, $out, $re);
		if($re) {
			return false;
		}
		else {
			return true;
		}
	}

	public function exists($path) {
		$cmd = $this->hadoopClient . " dfs -stat $path | wc -l";
		$fp = popen($cmd, "r");
		$count = trim(fgets($fp));
		if($count){
			return true;
		}
		else{
			return false;
		}
	}

	public function rm($path, $r=true) {
		if($r) {
			$cmd = $this->hadoopClient . " dfs -rmr $path";
		}
		else{
			$cmd = $this->hadoopClient . " dfs -rm $path";
		}
		exec($cmd, $out, $re);
		if($re) {
			return false;
		}
		else {
			return true;
		}
	}

	public function rename($path, $dest) {
		$cmd = $this->hadoopClient . " dfs -mv $path $dest";
		exec($cmd, $out, $re);
		if($re) {
			return false;
		}
		else {
			return true;
		}
	}

	public function chown($path, $owner, $group) {
		if($group) {
			$cmd = $this->hadoopClient . " dfs -chown $owner:$group $path";
		}else{
			$cmd = $this->hadoopClient . " dfs -chown $owner $path";
		}
		exec($cmd, $out, $re);
		if($re) {
			return false;
		}
		else {
			return true;
		}
	}
}